// ==UserScript==
// @name         Travian 一键复制集结点来村攻击
// @namespace    https://www.btravian.com/
// @version      0.3.8
// @description  Travian 一键复制集结点来村攻击
// @author       xinyin025
// @include        *://*.travian.*/build.php*gid=16*
// @exclude     *.css
// @exclude     *.js
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    function ajaxRequest(url, aMethod, param, onSuccess, onFailure) {
        var aR = new XMLHttpRequest();
        aR.onreadystatechange = function() {
            if( aR.readyState == 4 && (aR.status == 200 || aR.status == 304)){
                onSuccess(aR);
            }else if (aR.readyState == 4 && aR.status != 200) onFailure(aR);
        };
        aR.open(aMethod, url, true);
        if (aMethod == 'POST') {
            aR.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
        }
        aR.send(param);
    }

    function getTimeNow(){
        var currentDate = new Date();
        var year = currentDate.getFullYear();
        var month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
        var day = currentDate.getDate().toString().padStart(2, '0');
        var hours = currentDate.getHours().toString().padStart(2, '0');
        var minutes = currentDate.getMinutes().toString().padStart(2, '0');
        var seconds = currentDate.getSeconds().toString().padStart(2, '0');
        var formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        return formattedDateTime;
    }
    function checkAttacks(attacked_id,attacked_X,attacked_Y,attacks,attack_data){
        for (var i = 0; i < attacks.length; i++) {
            var attacker = attacks[i].getElementsByTagName("thead")[0].getElementsByTagName("td")[1].getElementsByTagName("a")[1];
            if(attacker === undefined){
                attacker = attacks[i].getElementsByClassName('troopHeadline')[0].innerText;
            }else{
                attacker = attacks[i].getElementsByTagName("thead")[0].getElementsByTagName("td")[1].getElementsByTagName("a")[1].innerHTML.split(" ")[0]
            }
            var attackerPosX = attacks[i].getElementsByClassName("coordinateX")[0].innerHTML.replaceAll("−", "-").replace(/[^\d-]/g, '');
            var attackerPosY = attacks[i].getElementsByClassName("coordinateY")[0].innerHTML.replaceAll("−", "-").replace(/[^\d-]/g, '');
            var attackTime = attacks[i].getElementsByClassName("at")[0];
            var troops = attacks[i].querySelector("tbody.units.last").innerText.split("\t");
            if(troops[9] === "0"){
                // 看到攻击兵种，并且没有忽悠，佯攻，将其标记为绿色
                var greenIco = attacks[i].querySelector('thead>tr>td.troopHeadline>a.markAttack>img').classList.contains("markAttack1");
                if(greenIco){
                    // 已被标记为绿色
                    attack_data.fackAttackNum ++;
                    continue;
                }
                var markBtn = attacks[i].querySelector('thead>tr>td.troopHeadline>a.markAttack');
                if(markBtn != undefined && !greenIco){
                    //markBtn.click();
                    attack_data.fackAttackNum ++;
                    continue;
                }
            }
            if (attackTime === undefined){
                attackTime = "00:00:00";
            }else{
                attackTime = attacks[i].getElementsByClassName("at")[0].innerHTML.replace(/[^\d:]/g, '');
            }
            attack_data.copyText += attacked_id + '\t' + attacked_X + '|' + attacked_Y + '\t' + attacker + '\t' + attackerPosX + '|' + attackerPosY + '\t' + attackTime + '\n';
            attack_data.attackNum ++;
        }
    }
    function runOnce(){
        var button = document.createElement("button");
        button.innerHTML = "复制来村攻击";
        button.style.position = 'absolute';
        button.style.top = "10px";
        button.style.left = "10px";
        button.style.width = 300;
        button.style.height = 300;
        button.style.padding = '10px';
        button.style.background = '#f0f0f0';
        button.style.display = 'block';
        button.style.zIndex = 99;

        // 2. Append somewhere
        var body = document.getElementsByClassName("contentPage")[0];
        body.appendChild(button);

        // 3. Add event handler
        button.addEventListener ("click", function() {
            var header = "防御方\t防御坐标\t攻击方\t\t\t攻击方坐标\t攻击到达时间\n";
            var attacked_id = document.getElementsByClassName("playerName")[0].innerHTML;
            var attacked_X = document.getElementById("sidebarBoxVillageList").getElementsByClassName("active")[0].getElementsByClassName("coordinateX")[0].innerHTML.replaceAll("−", "-").replace(/[^\d-]/g, '');
            var attacked_Y = document.getElementById("sidebarBoxVillageList").getElementsByClassName("active")[0].getElementsByClassName("coordinateY")[0].innerHTML.replaceAll("−", "-").replace(/[^\d-]/g, '');
            var attacks = document.getElementsByClassName("inAttack");
            var raids = document.getElementsByClassName("inRaid");
            var attack_data = {attackNum : 0,fackAttackNum : 0,copyText:""};
            checkAttacks(attacked_id,attacked_X,attacked_Y,attacks,attack_data);
            checkAttacks(attacked_id,attacked_X,attacked_Y,raids,attack_data);
            if(attack_data.attackNum > 0){
                navigator.clipboard.writeText(header + attack_data.copyText);
                alert("复制 "+attack_data.attackNum+" 波来村攻击，并有 " + attack_data.fackAttackNum + " 波佯攻,佯攻已标记为绿色!");
            }else{
                alert("未发现真攻！已将佯攻标记为绿色");
            }
        });
    }

    runOnce();

})();